package com.zf.zfed.audit.ui

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zf.sqlite.utils.AppDatabase
import com.zf.sqlite.utils.WhitelistEntity
import com.zf.zfed.audit.R
import com.zf.zfed.audit.data.SignalType
import com.zf.zfed.audit.utils.DatabaseInitializer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class WhitelistActivity : AppCompatActivity() {
    
    private lateinit var recyclerView: RecyclerView
    private lateinit var emptyStateLayout: android.widget.LinearLayout
    private lateinit var adapter: WhitelistAdapter
    private lateinit var database: AppDatabase
    private var whitelistItems = mutableListOf<WhitelistEntity>()
    private var settingsPopup: PopupWindow? = null
    private var addWhitelistDialog: Dialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_whitelist)
        
        initViews()
        initDatabase()
        setupRecyclerView()
        loadWhitelistData()
        setupClickListeners()
    }

    private fun initViews() {
        recyclerView = findViewById(R.id.rv_whitelist)
        emptyStateLayout = findViewById(R.id.ll_empty_state)
    }

    private fun initDatabase() {
        database = AppDatabase.getInstance(this) ?: run {
            Toast.makeText(this, "数据库初始化失败", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        // 初始化测试数据
        DatabaseInitializer.initializeTestData(database)
    }

    private fun setupRecyclerView() {
        adapter = WhitelistAdapter(whitelistItems) { whitelistItem ->
            showRemoveConfirmDialog(whitelistItem)
        }
        
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter
    }

    private fun loadWhitelistData() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val items = database.whitelistDao().getAllWhitelist()
                withContext(Dispatchers.Main) {
                    whitelistItems.clear()
                    whitelistItems.addAll(items)
                    adapter.updateData(whitelistItems)
                    updateEmptyState()
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@WhitelistActivity, "加载白名单数据失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun updateEmptyState() {
        if (whitelistItems.isEmpty()) {
            recyclerView.visibility = android.view.View.GONE
            emptyStateLayout.visibility = android.view.View.VISIBLE
        } else {
            recyclerView.visibility = android.view.View.VISIBLE
            emptyStateLayout.visibility = android.view.View.GONE
        }
    }

    private fun setupClickListeners() {
        findViewById<android.widget.ImageView>(R.id.iv_back).setOnClickListener {
            finish()
        }
        
        findViewById<android.widget.ImageView>(R.id.iv_settings).setOnClickListener {
            showSettingsPopup(it)
        }
    }

    private fun showRemoveConfirmDialog(whitelistItem: WhitelistEntity) {
        AlertDialog.Builder(this)
            .setTitle("确认移除")
            .setMessage("确定要从白名单中移除设备 \"${whitelistItem.device_name}\" 吗？")
            .setPositiveButton("确定") { _, _ ->
                removeFromWhitelist(whitelistItem)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun removeFromWhitelist(whitelistItem: WhitelistEntity) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                database.whitelistDao().deleteWhitelist(whitelistItem)
                withContext(Dispatchers.Main) {
                    whitelistItems.remove(whitelistItem)
                    adapter.updateData(whitelistItems)
                    updateEmptyState()
                    Toast.makeText(this@WhitelistActivity, "已从白名单中移除", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@WhitelistActivity, "移除失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun showSettingsPopup(anchorView: View) {
        val popupView = LayoutInflater.from(this).inflate(R.layout.popup_settings_menu, null)
        
        settingsPopup = PopupWindow(
            popupView,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            true
        ).apply {
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            isOutsideTouchable = true
            isFocusable = true
        }
        
        // 设置按钮点击事件
        popupView.findViewById<Button>(R.id.btn_add_whitelist).setOnClickListener {
            settingsPopup?.dismiss()
            showAddWhitelistDialog()
        }
        
        popupView.findViewById<Button>(R.id.btn_batch_remove).setOnClickListener {
            settingsPopup?.dismiss()
            showBatchRemoveDialog()
        }
        
        // 测量弹窗的实际宽度
        popupView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        val popupWidth = popupView.measuredWidth

        // 获取设置按钮的屏幕位置
        val location = IntArray(2)
        anchorView.getLocationOnScreen(location)
        val anchorX = location[0]
        val anchorY = location[1]
        val anchorWidth = anchorView.width
        val anchorHeight = anchorView.height

        // 计算弹窗的显示位置
        // 使弹窗的右边缘与设置按钮的右边缘对齐
        val x = anchorX + anchorWidth - popupWidth
        // 弹窗显示在设置按钮下方，留8dp间距
        val y = anchorY + anchorHeight + (8 * resources.displayMetrics.density).toInt()

        settingsPopup?.showAtLocation(anchorView, Gravity.NO_GRAVITY, x, y)
    }

    private fun showAddWhitelistDialog() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_whitelist, null)
        
        addWhitelistDialog = Dialog(this).apply {
            setContentView(dialogView)
            window?.setLayout(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            window?.setDimAmount(0.0f) // 确保不添加遮罩效果
            setCancelable(true)
        }
        
        val spinnerSignalType = dialogView.findViewById<Spinner>(R.id.spinner_signal_type)
        val etMacAddress = dialogView.findViewById<EditText>(R.id.et_mac_address)
        val etRemarks = dialogView.findViewById<EditText>(R.id.et_remarks)
        val btnCancel = dialogView.findViewById<Button>(R.id.btn_cancel)
        val btnConfirm = dialogView.findViewById<Button>(R.id.btn_confirm)
        
        // 设置信号类型下拉框
        val signalTypes = SignalType.getAllTypes()
        val adapter = SignalTypeAdapter(this, signalTypes)
        spinnerSignalType.adapter = adapter
        
        // 设置下拉框背景
        spinnerSignalType.setPopupBackgroundResource(R.drawable.bg_spinner_dropdown)
        
        // 监听选择变化
        spinnerSignalType.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                adapter.setSelectedPosition(position)
            }
            
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        
        // 设置按钮点击事件
        btnCancel.setOnClickListener {
            addWhitelistDialog?.dismiss()
        }
        
        btnConfirm.setOnClickListener {
            val selectedType = signalTypes[spinnerSignalType.selectedItemPosition]
            val macAddress = etMacAddress.text.toString().trim()
            val remarks = etRemarks.text.toString().trim()
            
            if (macAddress.isEmpty()) {
                Toast.makeText(this, "请输入MAC地址", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            
            addWhitelistToDatabase(selectedType.id, macAddress, remarks)
            addWhitelistDialog?.dismiss()
        }
        
        addWhitelistDialog?.show()
    }

    private fun addWhitelistToDatabase(type: Int, macAddress: String, remarks: String) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val whitelistItem = WhitelistEntity(type, "", macAddress, "", remarks)
                database.whitelistDao().insertWhitelist(whitelistItem)
                
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@WhitelistActivity, "添加白名单成功", Toast.LENGTH_SHORT).show()
                    loadWhitelistData()
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@WhitelistActivity, "添加白名单失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun showBatchRemoveDialog() {
        AlertDialog.Builder(this)
            .setTitle("批量移除")
            .setMessage("确定要移除所有选中的白名单项吗？")
            .setPositiveButton("确定") { _, _ ->
                // TODO: 实现批量删除逻辑
                Toast.makeText(this, "批量删除功能待实现", Toast.LENGTH_SHORT).show()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    override fun onResume() {
        super.onResume()
        // 每次回到页面时刷新数据
        loadWhitelistData()
    }

    override fun onDestroy() {
        super.onDestroy()
        settingsPopup?.dismiss()
        addWhitelistDialog?.dismiss()
    }
}
